﻿using System.Threading.Tasks;
using MongoDB.Driver;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.Synchronization.Validation.Handlers.Common;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.Handlers.Events
{
    public class ControversyCorporateDataLoader
    {
        private readonly IMongoCollection<CompanyProfileResearchState> mongoCollection;
        private readonly ControversyCompanies controversyCompanies;
        WhiteListCompanies whiteListCompanies;

        public ControversyCorporateDataLoader(IMongoCollection<CompanyProfileResearchState> mongoCollection, ControversyCompanies controversyCompanies, WhiteListCompanies whiteListCompanies)
        {
            this.mongoCollection = mongoCollection;
            this.controversyCompanies = controversyCompanies;
            this.whiteListCompanies = whiteListCompanies;
        }

        public async Task LoadAsync()
        {
            var values = await mongoCollection.Find(Builders<CompanyProfileResearchState>.Filter.Where(x => x.ControversyResearchState.ResearchState == ResearchState.ResearchAvailable))
                .Project(x => new
                {
                    Id = x.Id,
                    CapitalIqId = x.CapitalIqId
                }).ToListAsync().ConfigureAwait(false);

            foreach (var value in values)
            {
                if (!controversyCompanies.Contains(value.Id) &&
                    !whiteListCompanies.Exists(x => x.CapitalIqId == value.CapitalIqId && x.ResearchProduct == BusinessResearchProduct.Events))
                    controversyCompanies.Add(value.Id);
            }
        }
    }
}
